//
//  EMConversationVCHelper.swift
//  easeIM-swift
//
//  Created by yangjian on 2022/7/20.
//

import UIKit
import RxSwift
import SwiftUI
import HyphenateChat

//let testUsername = "yy2"


class EMConversationVCHelper: NSObject {

    
    var models = [EMConversationCellModel]()
    
    var modelsMap : [String : EMConversationCellModel] = [String : EMConversationCellModel]()

    
    let willReloadTableViewLock = NSObject()
    var willReloadTableView = false
    
    //单位:秒 将要刷新的时候,先做延迟,延迟过程中可能再次需要刷新,这样可将多次刷新合并为1次.做一轮缓冲
    let intervalBeforeReload = 0.2

    
    
    var modelsSubject = BehaviorSubject<[EMConversationCellModel]>(value: [EMConversationCellModel]())
    var bag = DisposeBag()
    
    
//    lazy var testconversation = EMClient.shared().chatManager?.getConversation(testUsername, type: .chat, createIfNotExist: true)
    
    override init() {
        super.init()
        RXEMObservableManager.share.chatObservable.rx_messagesDidReceive.subscribe(onNext: {[unowned self] messages in
            //test==========
//            for message in messages {
//                if message.conversationId == testUsername {
//                    guard let body = message.body as? EMTextMessageBody else{continue}
//                    print("收到了一条消息:[\(message.conversationId)] -- [\(body.text)]")
//                    let fetchMsgs = testconversation?.loadMessagesStart(fromId: nil, count: 20, searchDirection: .up)
//                    guard let fetchbody = fetchMsgs?.last?.body as? EMTextMessageBody else{continue}
//                    print("拉取本地消息的最后一条消息:[\(fetchMsgs?.last?.conversationId)] -- [\(fetchbody.text)]")
//                    guard let lastbody = testconversation?.latestMessage.body as? EMTextMessageBody else{continue}
//                    print("直接从会话获取最新一条消息:[\(testconversation?.conversationId)] -- [\(lastbody.text)]")
//
//                    if fetchbody.text == lastbody.text {
//                        print("result--相同,没有问题")
//                    }else{
//                        print("result--不同⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️")
//                    }
//                }
//            }
            //test==========
            var newMessages = [EMChatMessage]()
            for message in messages {
                if self.modelsMap.keys.contains(message.conversationId) {continue}
                newMessages.append(message)
            }
            for newMsg in newMessages {
                var conversationType = EMConversationType.chat
                if newMsg.chatType == .chat {
                    conversationType = EMConversationType.chat
                }else if newMsg.chatType == .groupChat {
                    conversationType = EMConversationType.groupChat
                }else if newMsg.chatType == .chatRoom {
                    conversationType = EMConversationType.chatRoom
                }else{
                    conversationType = EMConversationType.chat
                }
                guard let conversation = EMClient.shared().chatManager?.getConversation(newMsg.conversationId, type: conversationType, createIfNotExist: true) else{
                    continue
                }
                self.modelsMap[conversation.conversationId] = EMConversationCellModel(conversation: conversation)
            }
            
            objc_sync_enter(self.willReloadTableViewLock)
            if self.willReloadTableView {
                objc_sync_exit(self.willReloadTableViewLock)
                print("等待刷新中...")
                return
            }
            self.willReloadTableView = true
            objc_sync_exit(self.willReloadTableViewLock)
            DispatchQueue.main.asyncAfter(deadline: .now() + self.intervalBeforeReload) {[unowned self] in
                self.models = self.modelsMap.values.sorted(by: {
                    $0.conversation?.latestMessage.timestamp ?? 0 > $1.conversation?.latestMessage.timestamp ?? 0
                })
                self.modelsSubject.onNext(self.models)
                objc_sync_enter(self.willReloadTableViewLock)
                self.willReloadTableView = false
                objc_sync_exit(self.willReloadTableViewLock)
            }
        }).disposed(by: bag)
    }
    
    func fetchConversations(){
        let conversations = EMClient.shared().chatManager?.getAllConversations() as? [EMConversation] ?? [EMConversation]()
//        conversations = conversations.sorted(by: { $0.latestMessage.timestamp > $1.latestMessage.timestamp })
        
        //从服务器获取
//        EMClient.share.chatManager.getConversationsFromServer { conversations , error in
//            let conversations = (conversations ?? [EMConversation]()) as [EMConversation]
//        }
        self.formatConversationCellModel(conversations: conversations)

    }
    
    func formatConversationCellModel(conversations : [EMConversation]){
//        var models = [EMConversationCellModel]()
        for conversation in conversations {
//            models.append(EMConversationCellModel(conversation: conversation))
            self.modelsMap[conversation.conversationId] = EMConversationCellModel(conversation: conversation)
        }
        models = self.modelsMap.values.sorted(by: {
            $0.conversation?.latestMessage.timestamp ?? 0 > $1.conversation?.latestMessage.timestamp ?? 0
        })
        self.modelsSubject.onNext(models)
    }
}
